import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { ElMessage } from "element-plus";

let children = [
  {
    path: '/home',
    component: () => import('../views/home.vue'),
  }, {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    }
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '角色管理'
    }
  },
  {
    path: '/admin',
    component: () => import('../views/admin/admin.vue'),
    meta: {
      title: '管理员管理'
    }
  }
]

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    component: () => import('../page/login.vue')
  },
  {
    path: '/index',
    component: () => import('../page/index.vue'),
    children,
  },
  // {
  //   path: '/:pathMatch(.*)*',
  //   redirect: sessionStorage.getItem('userInfo') ? '/home' : '/login'
  // }
]


const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    next();
    return;
  }

  let userInfo: any = sessionStorage.getItem('userInfo');
  if (!userInfo) {
    ElMessage.warning('请先登录');
    next('/login');
    return;
  }

  let menus_url = JSON.parse(userInfo).menus_url;
  menus_url.push('/home');
  if (!menus_url.find((item: String) => item == to.path) && children.find(item => item.path == to.path)) {
    ElMessage.warning('您没有访问权限');
    next(from.path);
    return;
  }

  next();
})

export default router
